package com.vedu.helper;

import com.diandian.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.io.Serializable;
import java.util.List;
import java.util.Locale;

/**
 * version: $Id: $
 *
 * @author yuancheng.li [create on 2018-01-06]
 */
@Component
public class MessageHelper {

    private static Logger logger = LoggerFactory.getLogger(MessageHelper.class);

    @Autowired
    private MessageSource messageSource;

    public <VO extends Serializable> Result<VO> resolveResultMsg(Result<VO> result) {

        Object[] args = null;
        return resolveResultMsg(result, args);
    }

    public <VO extends Serializable> Result<VO> resolveResultMsg(Result<VO> result, Object[] args) {

        String msg = null;
        if (result == null || StringUtils.isEmpty(msg = result.getMsg())) {
            return result;
        }
        Locale locale = LocaleContextHolder.getLocale();
        String message = messageSource.getMessage(msg, args, locale);
        logger.debug(msg + "==>" + message);
        result.setMsg(message);

        return result;
    }

    public <VO extends Serializable> Result<VO> resolveResultMsg(Result<VO> result, BindingResult error) {

        if (result == null || error == null) {
            return result;
        }
        Locale locale = LocaleContextHolder.getLocale();
        StringBuffer buffer = new StringBuffer();
        List<FieldError> fieldErrors = error.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            String message = messageSource.getMessage(defaultMessage, null, locale);
            buffer.append(message).append("|");
        }
        result.setMsg(buffer.toString());

        return result;
    }
}
